/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.tushen.labor;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tushen.labor.adapter.ItemAdapter;
import com.tushen.labor.adapter.WeatherItemAdapter;
import com.tushen.labor.bean.Person;
import com.tushen.labor.bean.Weather;
import com.tushen.labor.bean.WeatherInfo;
import com.tushen.labor.data.DataListener;
import com.tushen.labor.data.DataManager;
import com.tushen.labor.util.AesEncryptUtils;
import com.tushen.labor.util.DateUtil;
import com.tushen.labor.util.DownloadProgressEvent;
import com.tushen.labor.util.Lunar;

import com.tushen.labor.view.DHealthyProgressView;
import com.tushen.labor.view.ViewAdjust;
import com.tushen.labor.viewinject.ViewUtils;

import org.apache.commons.codec.binary.StringUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.*;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    private Activity mContext;
    private View rootView;

    private LayoutInflater mInflater;
    private final MyHandler mHandler = new MyHandler(this);

    private GridView gridViewIn;
    private GridView gridViewOut;
    private GridView gridViewWeather;

    private DHealthyProgressView progressView;

    private UdpReceiveThread udpReceiveThread;

    private final static int RECEIVE_PORT = 53212;

    private boolean listenStatus = false;

    private String receiveInfo;

    private DatagramSocket receiveSocket;

    //private StatInfoThread statInfoThread;

    private String deviceIp = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //EventBus.getDefault().register(this);
        mContext = this;
        mInflater = LayoutInflater.from(this);
        rootView = findViewById(R.id.root_layout);
        ViewAdjust.adjustLayoutParams(this, rootView);
        ViewUtils.inject(this, rootView);

        gridViewIn = findViewById(R.id.grid_in);
        gridViewIn.setAdapter(new ItemAdapter(mInflater));

        gridViewOut = findViewById(R.id.grid_out);
        gridViewOut.setAdapter(new ItemAdapter(mInflater));

        gridViewWeather = findViewById(R.id.weather_gv);
        gridViewWeather.setAdapter(new WeatherItemAdapter(mInflater));

        progressView = findViewById(R.id.kaoqinlv_progress);
        progressView.beginContinue(true);
        progressView.setInterpolator(new AccelerateInterpolator());

        //DataManager.getInstance().setHandler(mHandler);

    }

    @Override
    public void onStart() {
        Log.d(TAG, "onStart ..");
        super.onStart();
        //DataManager.getInstance().start();
        mHandler.sendEmptyMessageDelayed(0, 500);
        mHandler.sendEmptyMessageDelayed(1, 100);
        //setDataListener();

        startAnimation(findViewById(R.id.gif_1));
        startAnimation(findViewById(R.id.gif_2));
        startAnimation(findViewById(R.id.gif_3));
        startAnimation(findViewById(R.id.gif_4));

        listenStatus = true;
        udpReceiveThread = new UdpReceiveThread();
        udpReceiveThread.start();

        progressView.setOnValueChangeListener(new DHealthyProgressView.OnValueChangeListener() {
            @Override
            public void onValueChange(float value) {
                int percent = (int)value;
                ((TextView) findViewById(R.id.chuqinlv)).setText(percent+ "%");
            }
        });

        //statInfoThread = new StatInfoThread();
        //statInfoThread.start();

    }

    private void startAnimation(ImageView v){
        Animation a = AnimationUtils.loadAnimation(mContext, R.anim.anim);
        a.setInterpolator( new LinearInterpolator()); //匀速执行
        v.startAnimation(a);//view.startAnimation 执行动画
        a.setFillAfter(true);//动画终止时停留在最后一帧，如果设置为false，则会回到最开始的位置
    }

    private void clearAnimation(ImageView v){
        v.clearAnimation();
    }

    @Override
    public void onResume() {
        Log.d(TAG, "onResume ..");
        super.onResume();

        //DataManager.getInstance().resetTime();

        rootView.setFocusable(true);
        rootView.requestFocus();
        rootView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_UP) {
                    return false;
                }
                Log.d(TAG, "rootView onKey keyCode = " + keyCode);

                if (KeyEvent.KEYCODE_BACK == keyCode) {
                    finish();
                    return true;
                }

                return false;
            }
        });

    }

//    private void setDataListener(){
//
//        DataManager.getInstance().setWeatherListener(new DataListener.WeatherListener() {
//            @Override
//            public void onDataChanged(List<WeatherInfo> list) {
//                Log.d(TAG, "WeatherInfo list = " + JSONObject.toJSONString(list));
//                try {
//                    List<WeatherInfo> newList = new ArrayList<>();
//                    if (list.size() <= 3) {
//                        newList.addAll(list);
//                    } else {
//                        newList.add(list.get(0));
//                        newList.add(list.get(1));
//                        newList.add(list.get(2));
//                    }
//
//                    ((WeatherItemAdapter) (gridViewWeather.getAdapter())).setList(newList);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadProgressEvent event) {

    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop ..");
        mHandler.removeMessages(0);
        mHandler.removeMessages(1);
        //DataManager.getInstance().stop();

        clearAnimation(findViewById(R.id.gif_1));
        clearAnimation(findViewById(R.id.gif_2));
        clearAnimation(findViewById(R.id.gif_3));
        clearAnimation(findViewById(R.id.gif_4));

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Log.d(TAG, "onDestroy ..");

        listenStatus = false;
        try {
            if (receiveSocket != null){
                receiveSocket.close();
            }
            if (udpReceiveThread != null) {
                udpReceiveThread.interrupt();
                udpReceiveThread.join(1000);
            }

//            if (statInfoThread != null) {
//                statInfoThread.interrupt();
//                statInfoThread.join(1000);
//            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG,e.getMessage());
        }
        udpReceiveThread = null;
//        statInfoThread = null;
    }

    /**
     * Instances of static inner classes do not hold an implicit
     * reference to their outer class.
     */
    private class MyHandler extends Handler {
        private final WeakReference<MainActivity> mActivity;

        public MyHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {

            MainActivity activity = mActivity.get();

            if (activity == null || msg == null) {
                return;
            }

            switch (msg.what) {
                case 0:

                    if (activity.findViewById(R.id.yangli_date) != null) {
                        TextView tv = activity.findViewById(R.id.yangli_date);
                        //tv.setText(String.format("%s", DateUtil.getMMDDStr()));
                    }
                    if (activity.findViewById(R.id.yangli_year) != null) {
                        TextView tv = activity.findViewById(R.id.yangli_year);
                        //tv.setText(String.format("阳历: %s年", DateUtil.getYYYYStr()));
                    }

                    Lunar lunar = new Lunar(Calendar.getInstance());
                    if (activity.findViewById(R.id.nongli_date) != null) {
                        TextView tv = activity.findViewById(R.id.nongli_date);
                        //tv.setText(lunar.toString());
                    }
                    if (activity.findViewById(R.id.nongli_year) != null) {
                        TextView tv = activity.findViewById(R.id.nongli_year);
                        //tv.setText(String.format("农历: %s年", lunar.cyclical()));
                    }

                    activity.mHandler.sendEmptyMessageDelayed(0, 300 * 1000);
                    break;
                case 1:
                    if (activity.findViewById(R.id.weather_time_tv) != null) {
                        TextView tv = activity.findViewById(R.id.weather_time_tv);
                        //tv.setText(String.format("%s", DateUtil.getNowHHmmssStr()));
                    }
                    activity.mHandler.sendEmptyMessageDelayed(1, 1000);
                    break;

            }
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        //在这个方法调用之前，view都没有被attach到ViewRoot上（也就没有show的概念），显示工作则是由WindowManagerService去控制的
        Log.d(TAG, "onAttachedToWindow called..mContext = " + mContext);
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        Log.d(TAG, "onDetachedFromWindow called..mContext = " + mContext);
    }

    MessageHandler handler = new MessageHandler(this);

    public class UdpReceiveThread extends Thread {

        private final String TAG = "UdpReceiveThread";

        public UdpReceiveThread(){
        }

        @Override
        public void run() {
            Log.d(TAG, "receiving... ");
            try {
                receiveSocket = new DatagramSocket(null);
                receiveSocket.setReuseAddress(true);
                receiveSocket.bind(new InetSocketAddress(RECEIVE_PORT));
                while (listenStatus){
                    byte data[] = new byte[1024*8];
                    DatagramPacket packet = new DatagramPacket(data, data.length);
                    receiveSocket.receive(packet); // 阻塞式，接收发送方的packet
                    //取出数据长度
                    int len = packet.getLength();

                    byte[] packetByte = packet.getData();
                    byte[] messageByte = new byte[len];
                    System.arraycopy(packetByte, 0, messageByte, 0, len);
                    String ip = packet.getAddress().getHostAddress();

                    receiveInfo = AesEncryptUtils.decryptByte(messageByte);
                    JSONObject jsonObject = JSONObject.parseObject(receiveInfo);
                    jsonObject.put("sendIP",ip);

                    //Log.d(TAG, "received:  " + jsonObject);

                    Message msg = Message.obtain();
                    msg.obj = jsonObject;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "run: " + e.getMessage());
            }

        }
    }

    private List<Person> inList = new ArrayList<>();

    private List<Person> outList = new ArrayList<>();

    private List<WeatherInfo> weatherInfoList = new ArrayList<>();

    public class MessageHandler extends Handler {

        private final WeakReference<MainActivity> mActivity;

        public MessageHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();

            if (activity == null || msg == null || msg.obj == null) {
                return;
            }

            JSONObject obj = (JSONObject) msg.obj;
            this.handleMessage(obj);
        }

        private void handleMessage(JSONObject jsonObject) {
            //JSONObject jsonObject = JSONObject.parseObject(message);
            Log.d(TAG, " massage: " + jsonObject);
            if (jsonObject != null){
                String type = jsonObject.getString("Type");
                deviceIp = jsonObject.getString("sendIP");
                ((TextView) findViewById(R.id.tv_ip)).setText("IP:" + deviceIp);
                JSONObject data = jsonObject.getJSONObject("Data");
                //String devID = jsonObject.getString("DevID");
                switch (type){
                    case "IAmAlive":
                        String ProjName = jsonObject.getString("ProjName");
                        if(ProjName !=null && !"".equals(ProjName)){
                            ((TextView) findViewById(R.id.title)).setText(ProjName);
                        }
                        hanleHeartbeat(data);
                        break;
                    case "ReportRecord":
                        hanleRecord(data);
                        break;
                    case "StatChange":
                        hanleStatChange(data);
                        break;
                }
            }else{
                Log.d(TAG, "空消息");
            }

        }

        private void hanleStatChange(JSONObject data) {
            Integer countTotal = 0;
            Integer attendCountTotal = 0;
            Integer presentCountTotal = 0;
            BigDecimal xm_rate = BigDecimal.ZERO;

            //登记人员
            Integer platTotalPersonNum = data.getInteger("RegisteredTotalPersonNum");
            if (platTotalPersonNum != null){
                countTotal = platTotalPersonNum < 0 ? 0 : platTotalPersonNum;
            }
            ((TextView) findViewById(R.id.total_person)).setText(countTotal + "");

            //在场实时人员
            Integer presentPersonNum = data.getInteger("PresentPersonNum");
            if (presentPersonNum != null ){
                presentCountTotal = (presentPersonNum < 0 ? 0 : presentPersonNum);
            }
            ((TextView) findViewById(R.id.current_person)).setText(presentCountTotal + "");

            //出勤人员
            Integer visitTodayPersonNum = data.getInteger("VisitTodayPersonNum");
            if (visitTodayPersonNum != null ){
                attendCountTotal = (visitTodayPersonNum < 0 ? 0 : visitTodayPersonNum);
            }
            ((TextView) findViewById(R.id.today_in)).setText(attendCountTotal + "");

            //今日出场
            Integer visitTodayOut = (visitTodayPersonNum - presentPersonNum) < 0 ? 0 : (visitTodayPersonNum - presentPersonNum);
            ((TextView) findViewById(R.id.today_out)).setText(visitTodayOut + "");

            //出勤率
            if (countTotal > 0){
                xm_rate = new BigDecimal(attendCountTotal).divide(new BigDecimal(countTotal),4,BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP);
            }

            float currValue = progressView.getmValue();
            float diff = xm_rate.floatValue() -currValue;
            progressView.setmValue(diff);

            JSONObject weatherJson =  data.getJSONObject("Weather");
            if (weatherJson != null) {
                weatherInfoList = getWeatherInfoList(weatherJson);
            }

            ((WeatherItemAdapter) (gridViewWeather.getAdapter())).setList(weatherInfoList);
        }

        // 组装天气数据
        private List<WeatherInfo> getWeatherInfoList(JSONObject result) {
            List<WeatherInfo> retList = new ArrayList<>();

            JSONObject realtime = result.getJSONObject("realtime");

            String hour = DateUtil.getNowHHStr();
            Integer houtInt = Integer.parseInt(hour);

            WeatherInfo weatherInfo;
            JSONArray jsonArray = result.getJSONArray("future");
            for (int i = 0; i < 3; i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                weatherInfo = new WeatherInfo();
                JSONObject jsonWid0 = jsonObject.getJSONObject("wid");
                String widHour0 = houtInt >= 18 ? jsonWid0.getString("night") : jsonWid0.getString("day");
                weatherInfo.setWeather(Weather.matchCode(widHour0));
                weatherInfo.setDateStr(jsonObject.getString("date"));
                weatherInfo.setWeekStr(DateUtil.getWeekOfDate(i));
                weatherInfo.setTemperatureRange(jsonObject.getString("temperature"));
                weatherInfo.setWindDescription(jsonObject.getString("direct"));
                retList.add(weatherInfo);
            }
            retList.get(0).setCurrTemperature(realtime.getString("temperature"));

            return retList;
        }

        //设备刷脸实时考勤
        private void hanleRecord(JSONObject data) {
            try {

               // Site = Site==null?"":Site;
                String FaceImgPath = data.getString("FaceImgPath");
                String UserName = data.getString("UserName");
                Long timeStamp = data.getLong("TimeStamp");
                boolean dir = data.getBoolean("Dir");
                String Company = data.getString("CompanyName");
                String WorkType = data.getString("WorkTypeName");
                String TeamName = data.getString("TeamName");
                String DevID = data.getString("DevID");
                //String Temperature = data.getString("Temperature");
                String faceImgPath = "http://" + deviceIp + "/ts/get_record_img?ImgPath=" + FaceImgPath + "&DevID=" + DevID;

                String time = DateUtil.formatTime(timeStamp == null ? 0L:timeStamp);
                Person person = new Person();
                person.setName(UserName);
                person.setCompanyName(Company);
                person.setGroupName(TeamName);
                person.setPosName(WorkType);
                person.setImageUrl(faceImgPath);
                person.setInoutTime(time);

                if (dir){
                    person.setInoutName("进场");
                    if (inList.size() == 4 ){
                        inList.remove(0);
                        inList.add(person);
                    }else {
                        inList.add(person);
                    }
                }else {
                    person.setInoutName("出场");
                    if (outList.size() == 4 ){
                        outList.remove(0);
                        outList.add(person);
                    }else {
                        outList.add(person);
                    }
                }

                ((ItemAdapter) (gridViewIn.getAdapter())).setList(inList);

                ((ItemAdapter) (gridViewOut.getAdapter())).setList(outList);

            } catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "人员进出详细信息展示出错" + e.getMessage());
            }

        }

        private void hanleHeartbeat(JSONObject data) {
            Log.d(TAG, "alive: "+ data.toJSONString());
            deviceIp = data.getString("IP");

            //((TextView) findViewById(R.id.tv_ip)).setText("IP：" + deviceIp);
        }

    }

    //启线程查询一次统计信息
//    public class StatInfoThread extends Thread {
//
//        private final String TAG = "StatInfoThread";
//
//        public StatInfoThread(){
//        }
//
//        boolean queryFlag = true;
//
//        @Override
//        public void run() {
//            Log.d(TAG, "query... ");
//            try {
//                while (queryFlag) {
//                    JSONObject jsonObject = handleQuery();
//                    Message msg = Message.obtain();
//                    msg.obj = jsonObject;
//                    statInfoHandler.sendMessage(msg);
//                    Thread.sleep(1000*5);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                Log.d(TAG, "run: " + e.getMessage());
//            }
//
//        }
//
//        //获取到发送方ip后，发http请求查询一次统计信息
//        private JSONObject handleQuery() {
//            if (deviceIp != null && !"".equals(deviceIp) && queryFlag) {
//               // deviceIp = "192.168.101.142";
//                String password = "admin";
//                String urlLogin = "http://" + deviceIp + "/ts/api/login";
//                String urlStatInfo = "http://" + deviceIp + "/ts/api/getStatInfo";
//                JSONObject tokenJson = getTokenFromDevice(urlLogin,password);
//                Integer code = tokenJson.getInteger("code");
//                if (0 == code){
//                    JSONObject data = tokenJson.getJSONObject("data");
//                    String token = data.getString("jwtToken");
//                    return getStatInfo(urlStatInfo,token);
//                }else if(401 == code){
//                    password = "zhgd" + DateUtil.getNowDDStr() + DateUtil.getNowHHStr() + DateUtil.getNowmmStr();
//                    tokenJson = getTokenFromDevice(urlLogin,password);
//                    code = tokenJson.getInteger("code");
//                    if (0 == code){
//                        JSONObject data = tokenJson.getJSONObject("data");
//                        String token = data.getString("jwtToken");
//                        return getStatInfo(urlStatInfo,token);
//                    }
//                }
//                return null;
//            }
//            return null;
//        }
//
//        private JSONObject getStatInfo(String url, String token) {
//            JSONObject statInfo = getStatInfoFromDevice(url, token);
//            Integer code = statInfo.getInteger("code");
//            if (0 == code) {
//                JSONObject statData = statInfo.getJSONObject("data");
//                queryFlag = false;
//                return statData;
//            }
//            return null;
//        }
//
//        private JSONObject getTokenFromDevice(String url,String password) {
//            JSONObject json = new JSONObject();
//            json.put("password", password);
//
//            String result = HttpRequest.post(url)
//                    .header("Content-Type", "application/json")//头信息，多个头信息多次调用此方法即可
//                    .body(json.toJSONString())
//                    .execute().body();
//            Log.d(TAG, "execute" + url);
//            return JSONObject.parseObject(result);
//        }
//
//        private JSONObject getStatInfoFromDevice(String url,String token) {
//            JSONObject json = new JSONObject();
//
//            String result = HttpRequest.post(url)
//                    .header("Content-Type", "application/json")//头信息，多个头信息多次调用此方法即可
//                    .header("Authorization","Bearer "+token)
//                    .body(json.toJSONString())
//                    .execute().body();
//            Log.d(TAG,"execute" +url);
//            return JSONObject.parseObject(result);
//        }
//
//    }
//
//    public class StatInfoHandler extends Handler {
//
//        private final WeakReference<MainActivity> mActivity;
//
//        public StatInfoHandler(MainActivity activity) {
//            mActivity = new WeakReference<>(activity);
//        }
//
//        @Override
//        public void handleMessage(Message msg) {
//            MainActivity activity = mActivity.get();
//
//            if (activity == null || msg == null || msg.obj == null) {
//                return;
//            }
//
//            JSONObject obj = (JSONObject) msg.obj;
//            this.handleMessage(obj);
//        }
//
//        private void handleMessage(JSONObject jsonObject) {
//            Log.d(TAG, " statInfo: " + jsonObject);
//            if (jsonObject != null){
//                hanleStatChange(jsonObject);
//            }else{
//                Log.d(TAG, "空消息");
//            }
//
//        }
//
//        private void hanleStatChange(JSONObject data) {
//            Integer countTotal = 0;
//            Integer attendCountTotal = 0;
//            Integer presentCountTotal = 0;
//            BigDecimal xm_rate = BigDecimal.ZERO;
//
//            //登记人员
//            JSONObject platTotalPersonNumJson = data.getJSONObject("PlatTotalPersonNum");
//            JSONObject platTotalPersonNum = platTotalPersonNumJson.getJSONObject("本地");
//            if (platTotalPersonNum != null){
//                countTotal = (platTotalPersonNum.getInteger("Num") < 0 ? 0 : platTotalPersonNum.getInteger("Num")) ;
//            }
//            ((TextView) findViewById(R.id.total_person)).setText(countTotal + "");
//
//            //在场实时人员
//            Integer presentPersonNum = data.getInteger("PresentPersonNum");
//            if (presentPersonNum != null ){
//                presentCountTotal = (presentPersonNum < 0 ? 0 : presentPersonNum);
//            }
//            ((TextView) findViewById(R.id.current_person)).setText(presentCountTotal + "");
//
//            //出勤人员
//            Integer visitTodayPersonNum = data.getInteger("VisitTodayPersonNum");
//            if (visitTodayPersonNum != null ){
//                attendCountTotal = (visitTodayPersonNum < 0 ? 0 : visitTodayPersonNum);
//            }
//            ((TextView) findViewById(R.id.today_in)).setText(attendCountTotal + "");
//
//            //今日出场
//            Integer visitTodayOut = (visitTodayPersonNum - presentPersonNum) < 0 ? 0 : (visitTodayPersonNum - presentPersonNum);
//            ((TextView) findViewById(R.id.today_out)).setText(visitTodayOut + "");
//
//            //出勤率
//            if (countTotal > 0){
//                xm_rate = new BigDecimal(attendCountTotal).divide(new BigDecimal(countTotal),4,BigDecimal.ROUND_HALF_UP)
//                        .multiply(new BigDecimal(100)).setScale(2,BigDecimal.ROUND_HALF_UP);
//            }
//
//            float currValue = progressView.getmValue();
//            float diff = xm_rate.floatValue() -currValue;
//            progressView.setmValue(diff);
//
//            JSONObject weatherJson =  data.getJSONObject("Weather");
//            if (weatherJson != null) {
//                weatherInfoList = getWeatherInfoList(weatherJson);
//            }
//
//            ((WeatherItemAdapter) (gridViewWeather.getAdapter())).setList(weatherInfoList);
//        }
//
//        // 组装天气数据
//        private List<WeatherInfo> getWeatherInfoList(JSONObject result) {
//            List<WeatherInfo> retList = new ArrayList<>();
//
//            JSONObject realtime = result.getJSONObject("realtime");
//
//            String hour = DateUtil.getNowHHStr();
//            Integer houtInt = Integer.parseInt(hour);
//
//            WeatherInfo weatherInfo;
//            JSONArray jsonArray = result.getJSONArray("future");
//            for (int i = 0; i < 3; i++) {
//                JSONObject jsonObject = jsonArray.getJSONObject(i);
//                weatherInfo = new WeatherInfo();
//                JSONObject jsonWid0 = jsonObject.getJSONObject("wid");
//                String widHour0 = houtInt >= 18 ? jsonWid0.getString("night") : jsonWid0.getString("day");
//                weatherInfo.setWeather(Weather.matchCode(widHour0));
//                weatherInfo.setDateStr(jsonObject.getString("date"));
//                weatherInfo.setWeekStr(DateUtil.getWeekOfDate(i));
//                weatherInfo.setTemperatureRange(jsonObject.getString("temperature"));
//                weatherInfo.setWindDescription(jsonObject.getString("direct"));
//                retList.add(weatherInfo);
//            }
//            retList.get(0).setCurrTemperature(realtime.getString("temperature"));
//
//            return retList;
//        }
//
//    }
//
//    StatInfoHandler statInfoHandler = new StatInfoHandler(this);

}
